package com.test.util;

import net.coobird.thumbnailator.Thumbnails;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

/**
 * @Author 绍展
 * @Date
 **/
public class ColorRecognUtil {

    //图片颜色识别
    public static String picFileRecog(String path){
        Map<String,Integer> colorCount=new HashMap<String, Integer>();
        String colors="";
        try {
            BufferedImage bi=Thumbnails.of(path).size(100,100).asBufferedImage();
//            BufferedImage bi=Thumbnails.of(path).scale(1).asBufferedImage();
//            bi=ColorUtil.filter(bi,1.0f,1.2f);
            int[] rgb;
            //统计图片中颜色标准的数量分布情况
            for(int w=0;w<bi.getWidth();w=w+2){
                for(int h=0;h<bi.getHeight();h=h+2){
                    //取出每个像素的rgb信息
                    rgb=changeToRgb(bi.getRGB(w,h));
                    //将rgb转为符合标准颜色表的十六进制形式
                    String hexColor=ColorUtil.changeRgb(rgb[0],rgb[1],rgb[2]);
                    //统计一下每个颜色的对应像素数量
                    Integer count=colorCount.get(hexColor);
                    if(count==null){
                        count=new Integer(0);
                    }
                    count++;
                    colorCount.put(hexColor,count);
                }
            }
            //取出数量最多的前五种颜色
            Map<Integer,String> colorCountRev=new HashMap<Integer, String>();
            List<Integer> countList=new ArrayList<Integer>();
            for(String key:colorCount.keySet()){
                colorCountRev.put(colorCount.get(key),key);
                countList.add(colorCount.get(key));
            }
            //排序
            Collections.sort(countList);
            int length=countList.size();
            if(length>5){
                length=5;
            }
            //取出数量最多的前五种颜色
           for(int i=1;i<=length;i++){
               if(i==1){
                   colors+=colorCountRev.get(countList.get(countList.size()-i));
               }else{
                   colors+=","+colorCountRev.get(countList.get(countList.size()-i));
               }
           }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return colors;
    }

    //将bufferImage取出来的rgb int值转为三位数的rgb
    public static int[] changeToRgb(int pixel){
        int[] rgb=new int[3];
        rgb[0] = (pixel & 0xff0000) >> 16;
        rgb[1] = (pixel & 0xff00) >> 8;
        rgb[2] = (pixel & 0xff);
        System.out.println(rgb[0]+","+rgb[1]+","+rgb[2]+","+pixel);
        return rgb;
    }



    public static void main(String[] args) {
        String colors=picFileRecog("F:\\work\\color\\20180615170308.jpg");
        System.out.println(colors);
    }
}
